<template>
  <div>
    <Row style="align-items: flex-start;margin-bottom:5px;display:block">
      <Col :lg="10" :xs="22" offset="0.5">
        <vxe-toolbar :refresh="{ query: reload }" print v-if="isUpdate">
          <template #buttons>
            <vxe-button size="mini" status="primary" @click="impotEvent"
              >导入</vxe-button
            >
            <vxe-button size="mini" status="primary" @click="exportFile"
              >导出</vxe-button
            >
            <vxe-button size="mini" status="primary" @click="addRow"
              >新增</vxe-button
            >
            <vxe-button size="mini" status="danger" @click="delRow"
              >删除</vxe-button
            >
            <vxe-button size="mini" @click="saveData">保存</vxe-button>
            <vxe-button size="mini" status="primary" @click="isShow = true"
              >挡位</vxe-button
            >
          </template>
        </vxe-toolbar>
        <vxe-table
          ref="xTable"
          class="sortable-row-demo"
          height="400"
          border
          :edit-rules="validRules"
          highlight-hover-row
          show-overflow
          :data="tablePage.listPage"
          :print-config="{}"
          :export-config="{
            filename: filename(),
            columnFilterMethod: filterExport1,
            type: 'cvs'
          }"
          :loading="loading"
          :edit-config="{ trigger: 'click', mode: 'cell' }"
        >
          <vxe-column type="checkbox" width="60"></vxe-column>
          <vxe-column width="60">
            <template #default>
              <span class="drag-btn">
                <i class="vxe-icon--menu"></i>
              </span>
            </template>
            <template #header>
              <vxe-tooltip
                v-model="showHelpTip1"
                content="按住后可以上下拖动排序！"
                enterable
              >
                <i
                  class="vxe-icon--question"
                  @click="showHelpTip1 = !showHelpTip1"
                ></i>
              </vxe-tooltip>
            </template>
          </vxe-column>
          <vxe-column
            field="pedal"
            title="油门开度(%)"
            :edit-render="{ name: 'input' }"
          ></vxe-column>
          <vxe-column
            v-for="config in tableColumn"
            :key="config.field"
            :field="config.field"
            :title="config.title"
            :edit-render="{ name: 'input' }"
          >
          </vxe-column>
        </vxe-table>
        <vxe-pager
          :current-page="tablePage.currentPage"
          :page-size="tablePage.pageSize"
          :total="tablePage.totalResult"
          :layouts="[
            'PrevPage',
            'JumpNumber',
            'NextPage',
            'FullJump',
            'Sizes',
            'Total'
          ]"
          @page-change="handlePageChange"
        >
        </vxe-pager>

        <br /><br />
        <vxe-toolbar :refresh="{ query: reload }" print v-if="isUpdate">
          <template #buttons>
            <vxe-button size="mini" status="primary" @click="impotEvent2"
              >导入</vxe-button
            >
            <vxe-button size="mini" status="primary" @click="exportFile2"
              >导出</vxe-button
            >
            <vxe-button size="mini" status="primary" @click="addRow2"
              >新增</vxe-button
            >
            <vxe-button size="mini" status="danger" @click="delRow2"
              >删除</vxe-button
            >
            <vxe-button size="mini" @click="saveData">保存</vxe-button>
            <vxe-button size="mini" status="primary" @click="isShow2 = true"
              >挡位</vxe-button
            >
          </template>
        </vxe-toolbar>
        <vxe-table
          ref="xTable2"
          height="400"
          class="sortable-row-demo"
          border
          :edit-rules="validRules"
          highlight-hover-row
          show-overflow
          :data="tablePage2.listPage"
          :print-config="{}"
          :export-config="{
            filename: filename(),
            columnFilterMethod: filterExport1,
            type: 'cvs'
          }"
          :loading="loading"
          :edit-config="{ trigger: 'click', mode: 'cell', enabled: isUpdate  }"
        >
          <vxe-column v-if="isUpdate" type="checkbox" width="60"></vxe-column>
          <vxe-column v-if="isUpdate" width="60">
            <template #default>
              <span class="drag-btn">
                <i class="vxe-icon--menu"></i>
              </span>
            </template>
            <template #header>
              <vxe-tooltip
                v-model="showHelpTip2"
                content="按住后可以上下拖动排序！"
                enterable
              >
                <i
                  class="vxe-icon--question"
                  @click="showHelpTip2 = !showHelpTip2"
                ></i>
              </vxe-tooltip>
            </template>
          </vxe-column>
          <vxe-column
            field="pedal"
            title="油门开度(%)"
            :edit-render="{ name: 'input' }"
          ></vxe-column>
          <vxe-column
            v-for="config in tableColumn2"
            :key="config.field"
            :field="config.field"
            :title="config.title"
            :edit-render="{ name: 'input' }"
          >
          </vxe-column>
        </vxe-table>
        <vxe-pager
          :current-page="tablePage2.currentPage"
          :page-size="tablePage2.pageSize"
          :total="tablePage2.totalResult"
          :layouts="[
            'PrevPage',
            'JumpNumber',
            'NextPage',
            'FullJump',
            'Sizes',
            'Total'
          ]"
          @page-change="handlePageChange2"
        >
        </vxe-pager>
      </Col>
      <Col :lg="12" :xs="22" offset="0.5">
        <div style="height:600px;margin-top: 100px;" id="c"></div>
      </Col>
    </Row>

    <!--    挡位名称管理-->
    <Modal v-model="isShow" title="挡位名称管理" @on-ok="ok">
      <vxe-button
        status="primary"
        @click="addNewCol"
        style="margin-bottom: 20px;"
        >新增</vxe-button
      >
      <br />
      <div
        v-for="config in tableColumn"
        :key="config.field"
        style="margin-bottom: 15px;"
      >
        <Input v-model="config.title">
          <Button
            @click="delCol(config.field)"
            slot="append"
            icon="md-trash"
          ></Button>
        </Input>
      </div>
    </Modal>
    <Modal v-model="isShow2" title="挡位名称管理" @on-ok="ok2">
      <vxe-button
        status="primary"
        @click="addNewCol2"
        style="margin-bottom: 20px;"
        >新增</vxe-button
      >
      <br />
      <div
        v-for="config in tableColumn2"
        :key="config.field"
        style="margin-bottom: 15px;"
      >
        <Input v-model="config.title">
          <Button
            @click="delCol2(config.field)"
            slot="append"
            icon="md-trash"
          ></Button>
        </Input>
      </div>
    </Modal>
  </div>
</template>

<script>
import { gearboxEfficiencyApi } from "@/api/gearbox-efficiency";
import { gearboxShiftApi } from "@/api/gearbox-shift";
import XLSX, { WorkSheet } from "xlsx";
import Sortable from "sortablejs";

export default {
  name: "ShiftGearMap",
  components: {},
  props: {
    gearboxId: {
      type: Number
    },
    isUpdate: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      showHelpTip1: false,
      sortable1: null,
      showHelpTip2: false,
      sortable2: null,
      isShow: false,
      tableColumn: [
        { field: "a1", title: "1->2" },
        { field: "a2", title: "2->3" },
        { field: "a3", title: "3->4" },
        { field: "a4", title: "4->5" },
        { field: "a5", title: "5->6" }
      ],
      tableData: [], // 表格列表数据
      tablePage: {
        currentPage: 1,
        pageSize: 10,
        totalResult: 0,
        listPage: []
      },
      loading: false,
      validRules: {
        inputSpeed: [{ pattern: "^[0-9]+.?[0-9]*$", message: "请输入数字类型" }]
      },

      isShow2: false,
      tableColumn2: [
        { field: "b1", title: "2->1" },
        { field: "b2", title: "3->2" },
        { field: "b3", title: "4->3" },
        { field: "b4", title: "5->4" },
        { field: "b5", title: "6->5" }
      ],
      tableData2: [], // 表格列表数据
      tablePage2: {
        currentPage: 1,
        pageSize: 10,
        totalResult: 0,
        listPage: []
      }
    };
  },
  watch: {
    /// 深度监听，可监听到对象、数组的变化  (table数据变化时，渲染echart)
    tableData: {
      handler(newVal, oldVal) {
        this.renderEchart();
      },
      deep: true // true 深度监听
    },
    tableData2: {
      handler(newVal, oldVal) {
        this.renderEchart();
      },
      deep: true // true 深度监听
    }
  },
  filters: {},
  created() {},
  mounted() {
    // 初始化数据
    this.initData();

    // 第一个table行移动
    this.rowDrop();

    this.rowDrop2();
  },
  methods: {
    rowDrop() {
      this.$nextTick(() => {
        const xTable = this.$refs.xTable;
        this.sortable1 = Sortable.create(
          xTable.$el.querySelector(".body--wrapper>.vxe-table--body tbody"),
          {
            handle: ".drag-btn",
            onEnd: ({ newIndex, oldIndex }) => {
              const currRow = this.tableData.splice(oldIndex, 1)[0];
              this.tableData.splice(newIndex, 0, currRow);
            }
          }
        );
      });
    },
    rowDrop2() {
      this.$nextTick(() => {
        const xTable = this.$refs.xTable2;
        this.sortable2 = Sortable.create(
          xTable.$el.querySelector(".body--wrapper>.vxe-table--body tbody"),
          {
            handle: ".drag-btn",
            onEnd: ({ newIndex, oldIndex }) => {
              const currRow = this.tableData2.splice(oldIndex, 1)[0];
              this.tableData2.splice(newIndex, 0, currRow);
            }
          }
        );
      });
    },
    initData() {
      gearboxShiftApi.getByGearboxId(this.gearboxId).then(res => {
        const data = res.data;
        if (data) {
          // 组合table数据
          const tableData1 = JSON.parse(data.tableData1);
          if (tableData1 && tableData1.length > 0) {
            this.tableData = tableData1;
          }
          const tableData2 = JSON.parse(data.tableData2);
          if (tableData2 && tableData2.length > 0) {
            this.tableData2 = tableData2;
          }
          this.findList();
          this.findList2();
          this.renderEchart();
        }
      });
    },

    saveData() {
      // 数据验证
      if (
        !(this.tableData && this.tableData.length > 0) &&
        !(this.tableData2 && this.tableData2.length > 0)
      ) {
        this.$Message.warning("没有可保存的数据！");
        return;
      }

      // 变速箱_id
      const gearboxId = this.gearboxId;

      const param = {
        tableData1: JSON.stringify(this.tableData),
        tableData2: JSON.stringify(this.tableData2),
        gearboxId: gearboxId
      };
      gearboxShiftApi.addGearboxShift(param).then(res => {
        this.$Message.warning("保存成功");
      });
    },

    delCol(field) {
      const temp = [];
      this.tableColumn.forEach(item => {
        if (item.field != field) temp.push(item);
      });
      this.tableColumn = temp;
    },
    addNewCol() {
      this.tableColumn.push({ field: "a" + new Date().getTime(), title: "" });
    },
    ok() {
      this.isShow = false;
    },
    delCol2(field) {
      const temp = [];
      this.tableColumn2.forEach(item => {
        if (item.field != field) temp.push(item);
      });
      this.tableColumn2 = temp;
    },
    addNewCol2() {
      this.tableColumn2.push({ field: "b" + new Date().getTime(), title: "" });
    },
    ok2() {
      this.isShow2 = false;
    },
    /**
     * @desc 挡位管理
     */
    gearMan() {},
    reRenderTable() {
      const newData = this.tablePage.listPage;
      this.tablePage.listPage = [];
      setTimeout(() => {
        this.tablePage.listPage = newData;
      }, 100);
    },
    reRenderTable2() {
      const newData = this.tablePage2.listPage;
      this.tablePage2.listPage = [];
      setTimeout(() => {
        this.tablePage2.listPage = newData;
      }, 100);
    },
    filename() {
      return (
        "换挡a" +
        new Date(+new Date() + 8 * 3600 * 1000)
          .toJSON()
          .substr(0, 19)
          .replace("T", "")
          .replaceAll("-", "")
          .replaceAll(":", "")
      );
    },
    exportFile() {
      this.$refs.xTable.exportData({ type: "csv" });
    },
    filename2() {
      return (
        "换挡b" +
        new Date(+new Date() + 8 * 3600 * 1000)
          .toJSON()
          .substr(0, 19)
          .replace("T", "")
          .replaceAll("-", "")
          .replaceAll(":", "")
      );
    },
    exportFile2() {
      this.$refs.xTable2.exportData({ type: "csv" });
    },
    filterExport1(data) {
      // 返回false 就是导出不显示
      if (!data.column.title) return false;
      if (data.column.type == "checkbox") return false;
      return true;
    },
    filterExport2(data) {
      // 返回false 就是导出不显示
      if (!data.column.title) return false;
      if (data.column.type == "checkbox") return false;
      return true;
    },

    // 导入
    impotEvent() {
      this.$refs.xTable
        .readFile({
          types: ["xls", "xlsx", "csv"]
        })
        .then(params => {
          const { files } = params;
          const fileReader = new FileReader();
          fileReader.onload = ev => {
            const data = ev.target.result;
            const workbook = XLSX.read(data, { type: "binary" });
            const csvData = XLSX.utils.sheet_to_csv(workbook.Sheets.Sheet1);
            const tableData = [];
            console.log("解析的输入：");
            // 解析数据csvData
            csvData.split("\n").forEach((vRow, index) => {
              if (index == 0) {
                return;
              }
              if (vRow) {
                const vCols = vRow.split(",");
                const item = {};
                vCols.forEach((val, cIndex) => {
                  if (cIndex == 0) {
                    item["pedal"] = val;
                  } else {
                    item["a" + cIndex] = val;
                  }
                  item["index"] = Number(
                    Math.random()
                      .toString()
                      .substr(2, 10) + Date.now()
                  ).toString(36);
                });
                tableData.push(item);
              }
            });
            this.tableData = tableData;
            this.findList();
          };
          fileReader.readAsBinaryString(files[0]);
        });
    },
    // 导入
    impotEvent2() {
      this.$refs.xTable2
        .readFile({
          types: ["xls", "xlsx", "csv"]
        })
        .then(params => {
          const { files } = params;
          const fileReader = new FileReader();
          fileReader.onload = ev => {
            const data = ev.target.result;
            const workbook = XLSX.read(data, { type: "binary" });
            const csvData = XLSX.utils.sheet_to_csv(workbook.Sheets.Sheet1);
            const tableData = [];
            console.log("解析的输入：");
            // 解析数据csvData
            csvData.split("\n").forEach((vRow, index) => {
              if (index == 0) {
                return;
              }
              if (vRow) {
                const vCols = vRow.split(",");
                const item = {};
                vCols.forEach((val, cIndex) => {
                  if (cIndex == 0) {
                    item["pedal"] = val;
                  } else {
                    item["b" + cIndex] = val;
                  }
                  item["index"] = Number(
                    Math.random()
                      .toString()
                      .substr(2, 10) + Date.now()
                  ).toString(36);
                });
                tableData.push(item);
              }
            });
            this.tableData2 = tableData;
            this.findList2();
          };
          fileReader.readAsBinaryString(files[0]);
        });
    },

    // 刷新表格
    reload() {
      const $table = this.$refs.xTable;
      // 清除所有状态
      $table.clearAll();
      // 初始化数据
      this.initData();
    },

    // 翻页
    handlePageChange({ currentPage, pageSize }) {
      this.tablePage.currentPage = currentPage;
      this.tablePage.pageSize = pageSize;
      this.findList();
    },
    handlePageChange2({ currentPage, pageSize }) {
      this.tablePage2.currentPage = currentPage;
      this.tablePage2.pageSize = pageSize;
      this.findList2();
    },

    findList() {
      // 总数据
      this.tablePage.totalResult = this.tableData.length;
      this.tablePage.listPage = this.tableData.slice(
        (this.tablePage.currentPage - 1) * this.tablePage.pageSize,
        this.tablePage.currentPage * this.tablePage.pageSize
      );
    },
    findList2() {
      // 总数据
      this.tablePage2.totalResult = this.tableData2.length;
      this.tablePage2.listPage = this.tableData2.slice(
        (this.tablePage2.currentPage - 1) * this.tablePage2.pageSize,
        this.tablePage2.currentPage * this.tablePage2.pageSize
      );
    },

    exportExcel1() {
      const workBook = XLSX.utils.table_to_book(
        this.$refs.xTable.$el.querySelector(".body--wrapper>.vxe-table--body")
      );
      XLSX.writeFile(workBook, "效率MAP.xlsx");
    },
    /// /////////////////////////////////////////第一个曲线 start
    /**
     * @desc 渲染echart--变速箱效率MAP
     * @sicne 2021/11/21
     */
    renderEchart() {
      const colors = [
        "#248EFD",
        "#C916F2",
        "#FD2446",
        "#1d953f",
        "#fab27b",
        "#ef5b9c",
        "#f58220",
        "#72baa7",
        "#ffe600",
        "#6c4c49"
      ];

      const lineDataObj = [];

      // 最终数据
      const series = [];

      // 挡位名 集合
      const fieldNams = [];

      // 计算曲线a表的曲线 -- 实线
      this.tableColumn.forEach(item => {
        const { field, title } = item;
        fieldNams.push(title);
        const tempArr = [];
        let tempTableData = [...this.tableData];
        tempTableData.sort((a, b) => a[field] - b[field]); // 排序
        tempTableData.forEach(item => {
          const temp = [];
          temp.push(item[field]);
          temp.push(item.pedal);
          tempArr.push(temp);
        });
        lineDataObj.push(tempArr);
      });

      lineDataObj.forEach((item, index) => {
        series.push({
          name: fieldNams[index],
          type: "line",
          smooth: true,
          symbolSize: 5,
          itemStyle: {
            normal: {
              color: colors[index],
              lineStyle: {
                color: colors[index]
              }
            }
          },
          lineStyle: {
            width: 2,
            shadowColor: "rgba(0,0,0,0.3)",
            shadowBlur: 10,
            shadowOffsetY: 2
            // type: "dashed"
          },
          data: item
        });
      });

      //= =====================
      const lineDataObj2 = [];
      // 计算曲线a表的曲线 -- 实线
      this.tableColumn2.forEach(item => {
        const { field } = item;
        const tempArr = [];

        let tempTableData2 = [...this.tableData2];
        tempTableData2.sort((a, b) => a[field] - b[field]); // 排序

        tempTableData2.forEach(item => {
          const temp = [];
          temp.push(item[field]);
          temp.push(item.pedal);
          tempArr.push(temp);
        });
        lineDataObj2.push(tempArr);
      });
      lineDataObj2.forEach((item, index) => {
        series.push({
          type: "line",
          name: fieldNams[index],
          smooth: true,
          symbolSize: 5,
          lineStyle: {
            width: 2,
            shadowColor: "rgba(0,0,0,0.3)",
            shadowBlur: 10,
            shadowOffsetY: 2,
            type: "dashed",
            color: colors[index]
          },
          data: item
        });
      });

      const option = {
        title: {
          text: "换挡MAP"
        },
        tooltip: {
          trigger: "item",
          formatter: function(item) {
            let str = "";
            str += `车速：${item.data[0]}<br/>油门开度：${item.data[1]}`;
            str += "<br/>";
            return str;
          }
        },
        legend: {
          x: "right",
          data: fieldNams,
          textStyle: {
            fontsize: 5
          }
        },
        grid: {
          left: "10%",
          right: "4%",
          bottom: "3%",
          containLabel: true
        },

        xAxis: {
          type: "value",
          name: "车速(km/h)",
          axisLine: { onZero: false },
          nameLocation: "center",
          splitLine: {
            show: false
          },
          nameGap: 25
        },
        yAxis: [
          {
            name: "油门开度(%)",
            axisLine: {
              lineStyle: {
                color: "#102b6a"
              },
              show: true
            },
            type: "value",
            position: "left",
            splitLine: {
              show: false
            }
          }
        ],
        series: series
      };

      let myChart = this.echarts.init(document.getElementById("c"));
      myChart.setOption(option);
    },

    /**
     * @desc 添加行数据
     */
    addRow() {
      const $table = this.$refs.xTable;
      const record = {
        pedal: null,
        index: new Date().getTime()
      };
      this.tableColumn.forEach(item => {
        record[item.field] = null;
      });
      this.tableData.push(record);
      const { row: newRow } = $table.insertAt(record, -1);
      this.findList();
      $table.setActiveCell(newRow, "gear");
      this.reRenderTable();
    },
    addRow2() {
      const $table = this.$refs.xTable2;
      const record = {
        pedal: null,
        index: new Date().getTime()
      };
      this.tableColumn2.forEach(item => {
        record[item.field] = null;
      });
      this.tableData2.push(record);
      const { row: newRow } = $table.insertAt(record, -1);
      this.findList2();
      // $table.setActiveCell(newRow, 'gear')
      this.reRenderTable2();
    },

    /**
     * @desc 删除行数据
     */
    async delRow() {
      const { rows } = await this.$refs.xTable.removeCheckboxRow();
      if (rows && rows.length > 0) {
        const newArr = [];
        const tempar = rows.map(item => item.index);
        this.tableData.forEach(item => {
          if (tempar.indexOf(item.index) == -1) {
            newArr.push(item);
          }
        });
        this.tableData = newArr;
      } else {
        this.$Message.warning("没有可删除的数据！");
      }
    },
    async delRow2() {
      const { rows } = await this.$refs.xTable2.removeCheckboxRow();
      if (rows && rows.length > 0) {
        const newArr = [];
        const tempar = rows.map(item => item.index);
        this.tableData2.forEach(item => {
          if (tempar.indexOf(item.index) == -1) {
            newArr.push(item);
          }
        });
        this.tableData2 = newArr;
      } else {
        this.$Message.warning("没有可删除的数据！");
      }
    }
  }
};
</script>
